import random
import time

# 共享变量，key是设备名称，value是账号
import os

from Util.log import Log


class AddFriendsFromContact:

    def __init__(self, device):
        self.device = device
        # 使用 d.watchers.run() 启动wather
        # self.device.watcher("添加到通讯录").when(text="添加到通讯录", className="android.widget.Button",
        #                                    resourceId="com.tencent.mm:id/ap0").click(text="添加到通讯录",
        #                                                                              className="android.widget.Button",
        #                                                                              resourceId="com.tencent.mm:id/ap0")

    def sleep(self):
        sleepTime = random.randint(1, 5)
        time.sleep(sleepTime)

    # 显示'添加好友'中'手机联系人'界面
    def showAddContactActivity(self):
        if self.showMoreMenu():
            if self.clickAddFriendsMenuItem():
                if self.activeContact():
                    return True

        return False

    # 点击主界面右上角的'+'按钮，显示'更多菜单'
    # private
    def showMoreMenu(self):
        from Util.log import Log
        Log.debug("显示'更多菜单'")
        uiObject = self.device(className="android.widget.RelativeLayout", description="更多功能按钮")
        if uiObject:
            uiObject.click_exists(timeout=10.0)
            return True
        else:
            Log.debug("未找到主界面的'+'按钮")
            return False

    # 点击主界面'更多菜单'中的'添加朋友菜单'
    # private
    def clickAddFriendsMenuItem(self):
        Log.debug("开始点击主界面'更多菜单'中的'添加朋友'菜单项")
        if self.device(index=1, className="android.widget.LinearLayout",
                       resourceId="com.tencent.mm:id/i8").click_exists(timeout=10.0):
            return True
        else:
            Log.debug("未找到'添加朋友'菜单项")
            return False

    # 激活'手机联系人'界面
    def activeContact(self):
        Log.debug("开始激活'手机联系人'界面")
        if self.device(text="手机联系人", className="android.widget.TextView",
                       resourceId="android:id/title").click_exists(timeout=10.0):
            return True
        else:
            Log.error("无法激活'手机联系人'界面")
            return False

    # 获取通讯录列表中子元素的个数
    def getContactList(self):
        Log.debug("获取通讯录列表")
        if self.device(className="android.widget.ListView",
                       resourceId="com.tencent.mm:id/b9a").wait():
            uiObject = self.device(className="android.widget.ListView",
                                   resourceId="com.tencent.mm:id/b9a")
            return uiObject
        else:
            Log.error("无法找到通讯录列表")
            return None

    # 添加联系人
    def addContact(self, contactList):
        Log.debug("开始获取联系人列表")
        # 获取所有的添加按钮
        for addButton in contactList.child(className="android.widget.FrameLayout", resourceId="com.tencent.mm:id/bc5"):
            # 点击添加按钮
            addButton.click_exists(timeout=10.0)

            self.inputValidationMessage("我是业主宝客服")
            self.sleep()

            self.clickFillMemoButton()

            self.clickSendButton()
            # 等待添加完成
            self.device.toast.get_message(5.0, 10.0, "已发送")
            self.sleep()
            # 后退到通讯录列表
            self.device(resourceId="com.tencent.mm:id/hs").click_exists(timeout=10.0)
            self.sleep()



    # 输入验证申请
    def inputValidationMessage(self, validationMessage):
        if self.device(className="android.widget.EditText", resourceId="com.tencent.mm:id/d4h").wait():
            uiObject = self.device(className="android.widget.EditText", resourceId="com.tencent.mm:id/d4h")
            uiObject.click()
            self.device.set_fastinput_ime(True)  # 切换成FastInputIME输入法
            self.device.clear_text()  # 清除输入框所有内容(Require android-uiautomator.apk version >= 1.0.7)
            self.device.send_keys(validationMessage)  # adb广播输入
            self.device.set_fastinput_ime(False)  # 切换成正常的输入法
            return True
        else:
            Log.debug("无法找到验证信息输入框")
            return False

    # 点击填写备注按钮
    def clickFillMemoButton(self):
        if self.device(className="android.widget.TextView", resourceId="com.tencent.mm:id/d4n").wait():
            self.device(className="android.widget.TextView", resourceId="com.tencent.mm:id/d4n").click_exists()
            return True

        Log.error("无法找到'设置备注和标签'按钮")
        return False

    # 点击'发送'按钮
    def clickSendButton(self):
        uiObject = self.device(className="android.widget.TextView", resourceId="com.tencent.mm:id/hg")
        if uiObject:
            uiObject.click_exists()
            return True
        else:
            Log.error("无法找到'发送按钮'")
            return False



    # 输入标签
    def inputTag(self, tag):
        if len(tag) == 0:
            return True
        actived = False
        # 找到标签控件
        uiObject = self.device(className="android.widget.TextView", resourceId="com.tencent.mm:id/arh")
        if uiObject:
            uiObject.click()  # 激活，进入输入状态
            actived = True
        else:
            uiObject = self.device(className="android.view.View", resourceId="com.tencent.mm:id/ari")
            if uiObject:
                uiObject.click()  # 激活，进入输入状态
                actived = True

        if actived:
            time.sleep(1)
            uiObject = self.device(text="添加标签", className="android.widget.EditText", resourceId="com.tencent.mm:id/hz")
            if uiObject:
                # 输入标签文字(解决无法输入中文的问题)
                # uiObject.set_text(tag)
                uiObject.click()
                os.system("adb shell am broadcast -a ADB_INPUT_TEXT --es msg '" + tag + "'")
                # 保存
                uiObject = self.device(text="保存", className="android.widget.TextView",
                                       resourceId="com.tencent.mm:id/hg")
                if uiObject:
                    uiObject.click()
                    return True
                else:
                    Log.error("无法找到'标签'的'保存'按钮")
                    return False
            else:
                Log.error("无法找到'添加标签'的文本框")
        else:
            Log.error("无法激活'输入标签'界面")
        return False
